import cfg from '../../config';
import {getView} from '../../util/api';
import {formatDate, getCurrDay, randomColor, isArrContain, isArrNoContain, findStr, backPage, getPrevDate, getNextDate, isSelector, message, closeMsg, getPinYin, getPassengers, strfind, hideIdcard, getJingTinInfoFun, tabSwitch, trainPact, removeArrEl} from '../../util/aid';
import {trips, orderStatus, orderCls, perKey, planKey} from '../const.config';
import {setHeadTrianInfo, loadJingTinInfoFun, getSeatParam} from '../common';

import {Slider, sliderHide, sliderShow} from '../../lib/kslider';
import * as ajax from '../../lib/kajax';
import Dialog from '../../lib/kdialog';

const dialog = new Dialog();

require('../../travel/travel.common');

const $ = require('../../lib/kdom');
let _view = require('raw-loader!./book.html');

const _url = '/train/book'; // 流转地址
let _data = null;//父页面的数据
let _opts = null;//父页面的参数
let _currSaet = null;
let _passArr = null; // 流转乘客数据
let _pidArr = []; // 选中乘客的PID
let totalPrice = 0;
let personNum = 0; // 总人数
// let stop = true;

export default class {
  path = '/train/book$';
  hash = '/train/book';
  title = '填写订单';

  constructor(opt) {
    opt = opt || {};
    this.path = opt.path || this.path;
    this.hash = opt.hash || this.hash;
    this.title = opt.title || this.title;
  }

  // 输出视图
  view(cb) {
    if (!_view) {
      // 静态资源浏览器有缓存,增加时标,强制刷新!
      getView(`${cfg.train.view.book}?t=${(+new Date())}`, '', (rs) => {
        _view = rs;
        cb(null, _view);
      });
    } else
      cb(null, _view);
  }

  // 在已经加载的视图上操作
  bind(dv, params) {
    // 测试
    params = params.data ? params : {"data": {"ID": "9", "TrainCode": "K590", "TrainType": "快速", "StartCity": "重庆", "StartTime": "22:00", "EndCity": "北京西", "EndTime": "05:18", "BeginStation": "重庆", "EndStation": "北京西", "Distance": "2073", "CostTime": "31时18分", "TDZ": "-", "YZ": "236", "WZ": "-", "RZ": "-", "RZ2": "-", "RZ1": "-", "YWS": "-", "YWZ": "-", "YWX": "444", "RWS": "-", "RWX": "674", "GWS": "-", "GWX": "-", "SWZ": "-", "TDZ_YP": "-1", "OverNight": "+2", "PriceCode": "-", "SeatCode": "-", "YZ_YP": "9", "RZ_YP": "0", "RZ2_YP": "-1", "RZ1_YP": "-1", "YW_YP": "9", "RW_YP": "9", "GW_YP": "0", "SWZ_YP": "-1", "WZ_YP": "0", "YZ_CODE": "101", "RZ_CODE": "-", "RZ2_CODE": "-", "RZ1_CODE": "-", "YW_CODE": "303", "RW_CODE": "402", "GW_CODE": "-", "SWZ_CODE": "-", "WZ_CODE": "-", "TDZ_CODE": "-"}, "opts": {"from": "CQW,重庆", "to": "BJP,北京", "date": "2017-07-14", "highMotor": false, "url": "/train/home"}};
    //
    console.log('我是预定页：', params);

    const regMobile = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
    const regUserName = /(^[\u4e00-\u9fa5]{1}[\u4e00-\u9fa5\.·。]{0,8}[\u4e00-\u9fa5]{1}$)|(^[a-zA-Z]{1}[a-zA-Z\s]{0,8}[a-zA-Z]{1}$)/;

    _data = params.data;
    _opts = params.opts || {};
    _passArr = params.passArr;

    // 初始化
    // 加载动画
    _pidArr = [];//清空用户的id

    // 设置头部信息
    setHeadTrianInfo(_data, _opts, trainBookBlockHead);

    // Saet
    loadViewDetail(_data);

    // 经停信息
    if ($.qu('#pg-train-book .jt-info')) {
      $.qu('#pg-train-book .jt-info').onclick = () => {
        dialog.loading();
        getJingTinInfoFun(_data.TrainCode, (rs) => {
          loadJingTinInfoFun(rs);
          sliderShow();
          dialog.close();
        });
      };
    }

    // 加载乘客
    loadPassFun(_passArr);

    // 保险价格改变
    baoXianVal.onchange = () => {
      calculatedPrice();
    };

    // 添加乘客
    bookAddPassBtn.onclick = () => {
      let data = {data: _data, opts: _opts, url: _url, passArr: _passArr || null, pidArr: _pidArr || null, currSaet: _currSaet};
      $.router.go('/train/passenger', data, true);
    };

    // 提交订单
    bookTickitBtn.onclick = () => {
      // console.log(_currSaet);
      if (_pidArr.length <= 0)return dialog.alert({content: '请选择乘客！'});
      if (!regUserName.test(userNameVal.value)) return dialog.alert({content: '请填写有效的和证件上相同的联系人的名字！'});
      if (!regMobile.test(mobileVal.value)) return dialog.alert({content: '请输联系人手机号！'});

      submitBookInfo(_data, _opts);
    };

    // backPage
    backPage('#pg-train-book', 'backPage', () => {
      if (_opts.keyword) {
        dialog.confirm({content: '您好！确定要放弃火车票改签吗？'}, (rs) => {
          if (rs) {
            $.router.go('/train/home', '', true);
          }
        });
      } else
        $.router.go('/train/list', {opts: _opts}, true);
    });

    bookTrainPactBtn.onclick = () => {
      trainPact((rs) => {
        if (rs) {
          new Slider({content: `<div style="padding: .75rem;"><span class="icon icon-left float-left fwn pl075 mt03 text-disabled" id="T_PactCancel">返回</span>${rs}</div>`});
          sliderShow();
          T_PactCancel.onclick = () => {
            sliderHide();
          };
        }
      });
    };

  }

  /*bind*/
}

window.delBookPassFun = (that, id, idx) => {
  if (idx) {
    bookAddPassBox.removeChild(that.parentNode);
    removeArrEl(_passArr, id);
    removeArrEl(_pidArr, id);
    handleTravleFun(_pidArr, _opts);
  }
};

// loadViewDetail
function loadViewDetail(data) {
  if (!data) return;
  let rs = getSeatParam(data);
  let rc = '';
  if (rs.length > 1) {
    rc += `<div class="buttons-tab books ${rs.length > 3 ? 'on' : ''}">`;
    for (let i = 0; i < rs.length; i++) {
      if (rs[i].price && rs[i].seat && rs[i].seatCode && rs[i].yuPiao !== '0') {
        if (i === 0) {
          _currSaet = rs[i];
          rc += `<input id="currSelectSaetValue" type="hidden" value='${JSON.stringify(rs[i])}'><div class="tab-link button active" data-val='${JSON.stringify(rs[i])}'>`;
        } else {
          rc += `<div class="tab-link button" data-val='${JSON.stringify(rs[i])}'>`;
        }
        rc += `<p>${rs[i].seat}</p>
                  <p><span class="f06">¥ </span>${rs[i].price}</p>
              </div>`;
      }
    }
    rc += `</div>`;
    $.html(allSaetBox, rc);
    tabSwitch($.qus('#allSaetBox .tab-link'), (that) => {
      currSelectSaetValue.value = that.getAttribute('data-val');
      _currSaet = JSON.parse(that.getAttribute('data-val'));
      calculatedPrice();
    });
  } else if (rs.length === 1) {
    _currSaet = rs[0];
    rc = `<input id="currSelectSaetValue" type="hidden" value='${JSON.stringify(rs[0])}'>
        <div class="list-block trainBlockM mb05 active">
            <ul>
                <li class="item-content">
                    <div class="item-inner">
                        <div class="item-title">${rs[0].seat}</div>
                        <div class="item-after"><span class="text-danger">￥<span>${rs[0].price}</span></span></div>
                    </div>
                </li>
            </ul>
        </div>`;
    $.html(allSaetBox, rc);
  }
}

/*
 $("body").bind('click', function(e) {
 var e = e || window.event; //浏览器兼容性
 var elem = e.target || e.srcElement;
 while (elem) { //循环判断至跟节点，防止点击的是div子元素
 if (elem.id && elem.id == 'shopbox') {
 return;
 }
 elem = elem.parentNode;
 }
 $("#shopbox").hide(); //点击的不是div或其子元素
 });
 }*/

// 计算价格
function calculatedPrice() {
  if (!_passArr) return;
  personNum = _passArr.length || 0;
  const baoXianPrice = Number(baoXianVal.value || 0);
  const currPrice = Number(_currSaet.price || 0);
  const baoXianNum = $.qus('#bookAddPassBox input[name="checkbox"]:checked').length || 0;
  // sum
  totalPrice = personNum * currPrice + baoXianNum * baoXianPrice;
  $.html(displyPriceVal, totalPrice);
}

// 提交订单
function submitBookInfo(_data, _opts) {
  if (!_passArr) return;
  dialog.loading();
  const baoXianNum = $.qus('#bookAddPassengerBox input[name="checkbox"]:checked').length || 0;
  let BOOK_URL = null;
  let _cardType = null;
  let _ageType = null;
  let _Insurancecount = 0;
  let _passenger = [];
  let chaiLv = '';
  let formData = '';

  // 判断是否改签
  if (_opts.keyword) {
    formData += `action=changeapply&orderno=${_opts.orderNo}`;
  } else {
    formData += 'action=createorder';
  }

  for (let i = 0, o = _passArr, len = o.length; i < len; i++) {
    _Insurancecount = 0;
    _cardType = o[i][perKey.IDType];
    _ageType = o[i][perKey.AgeType];
    if (strfind(_cardType, '身份证')) {
      _cardType = 1;
    } else if (strfind(_cardType, '护照')) {
      _cardType = 2;
    } else if (strfind(_cardType, '港澳通行证')) {
      _cardType = 5;
    } else if (strfind(_cardType, '台湾居民来往大陆通行证')) {
      _cardType = 7;
    }

    if ($.id(`passenger_${o[i][perKey.id]}`).checked) {
      _Insurancecount = 1;
    }

    if (strfind(_ageType, '成人')) {
      _ageType = 1;
    } else if (strfind(_ageType, '儿童')) {
      _ageType = 2;
    }

    _passenger.push({'passengerName': o[i][perKey.Name], 'passengerIdCardType': `${_cardType}`, 'passengerIdCardNum': o[i][perKey.IDNo], 'Insurancecount': _Insurancecount, 'TicketType': `${_ageType}`});
  }

  if ($.id('bookTravleSelectVal').checked) {
    chaiLv = `{"Personal":"${publicPrivate.value || ''}","TripType":"${TripType.value || ''}","TripReason":"${TripReason.value || ''}","TripNote":"${TripNote.value || ''}"}`;
  } else {
    chaiLv = `{Personal:'0',TripType:'',TripReason:'',TripNote:''}`;
    dialog.alert({content: '尊敬的旅客：您还不是差旅用户，暂时无法预定车票！'});
    return;
  }

  formData += `&contactname=${userNameVal.value}&contactmobile=${mobileVal.value}&ticketcount=${personNum}&totalprice=${totalPrice}&traincode=${_data.TrainCode}&fromstation=${_data.StartCity}&tostation=${_data.EndCity}&sdate=${_opts.date}&insurancenum=${baoXianNum}&seatname=${_currSaet.seat}&seatcode=${_currSaet.seatCode}&passenger=${JSON.stringify(_passenger)}&xhParam=${chaiLv}`;

  console.log(formData);

  // 测试
  ajax.post(`${cfg.train.host}${cfg.train.postAct}`, formData, (err, rs) => {
    if (rs) {
      dialog.close();
      // console.log(rs);
      let r = JSON.parse(rs);
      if (r.successcode === 'T') {
        $.router.go('/train/payorder', {data: _data, opts: _opts, order: r.data, currSaet: _currSaet}, true);
      } else {
        dialog.alert({content: r.Info || '非常抱歉，订单预定失败，请刷新或者退出重试！'});
      }
    }
  });
}

// 加载乘客
function loadPassFun(data) {
  if (data) {
    // console.log(data);
    let rc = '';
    for (let i = 0, o = data, len = o.length; i < len; i++) {
      _pidArr.push(o[i][perKey.id]);
      rc += `<li class="flex-block">
                <label class="label-checkbox item-content">
                    <input type="checkbox" name="checkbox" onchange="personBaoXian()" id="passenger_${o[i][perKey.id]}">
                    <div class="item-media"><i class="icon icon-form-checkbox"></i></div>
                    <div class="item-inner">
                        <div class="item-title-row">
                            <div class="item-title">
                                ${o[i][perKey.Name]}&nbsp;&nbsp;${hideIdcard(o[i][perKey.IDNo]).hide}
                            </div>
                        </div>
                        <div class="item-subtitle text-disabled">选择保险&nbsp;<span class="f06">（成人）</span></div>
                    </div>
                </label>
                <span class="weui_icon_cancel opt_button text-danger" onclick="delBookPassFun(this,'${o[i][perKey.id]}','${i}')"></span>
            </li>`;
    }
    $.html(bookAddPassBox, rc);
    handleTravleFun(_pidArr, _opts);
    calculatedPrice();
  }
}
// 处理差旅
function handleTravleFun(pidArr, opts) {
  // console.log('处理差旅:', pidArr, opts);
  if (pidArr.length <= 0) return optTravelFun({});
  // 获取乘客
  let strokeInfo = {from: opts.from, to: opts.to, danChengDate: opts.date, fanChengDate: '', roundTrip: 1, tickitType: 1};
  getPassengers((rs) => {
    if (rs) {
      let rc = CheckTravelPolicyFun(rs, pidArr, strokeInfo);
      console.log(rc);
      optTravelFun(rc);
    } else {
      dialog.alert({content: cfg.train.warnMsg});
    }
  });

  // 测试数据
  // getPinYin((pinyin) => {
  //   if (jsonPass) {
  //     let rc = CheckTravelPolicyFun(jsonPass, pidArr, strokeInfo);
  //     console.log(rc);
  //     optTravelFun(rc);
  //   } else {
  //     dialog.alert({content: cfg.train.warnMsg});
  //   }
  // });
}
// 操作差旅
function optTravelFun(rs) {
  const tag = $.qu('#bookHintInfoBox .bookHintMsg');
  if (rs.status) {//差旅
    bookTravleSelectbox.style.display = 'block';
    bookHintInfoBox.style.display = 'none';
    $.id('bookTravleSelectVal').checked = true;
    publicPrivate.value = 2;
    $.id('bookTravleSelectVal').removeAttribute('disabled');
    publicPrivate.removeAttribute('disabled');

    // stop = true;
    $.html(tag, '');
  } else {//非差旅
    if (rs.msgCode) {
      bookTravleSelectbox.style.display = 'none';
      bookHintInfoBox.style.display = 'block';
      $.id('bookTravleSelectVal').checked = false;
      publicPrivate.value = 0;
      $.id('bookTravleSelectVal').setAttribute('disabled', true);
      publicPrivate.setAttribute('disabled', true);

      // stop = false;
      $.html(tag, rs.msg);
    } else {
      bookTravleSelectbox.style.display = 'none';
      bookHintInfoBox.style.display = 'none';
      $.id('bookTravleSelectVal').checked = false;
      publicPrivate.value = 0;
      $.id('bookTravleSelectVal').setAttribute('disabled', true);
      publicPrivate.setAttribute('disabled', true);

      $.html(tag, '');
    }

    /* if (rs.insurance) {

     } else {

     }*/
  }
}
// 操作保险
function optInsuranceFun(val) {
}
// 乘客选中保险
window.personBaoXian = () => {
  calculatedPrice();
};